package com.edu.spider.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.edu.spider.DTO.SearchCTripTrainDTO;
import com.edu.spider.enity.SearchLog;
import com.edu.spider.enity.TrainInfo;
import com.edu.spider.enity.TrainItem;
import com.edu.spider.mapper.SearchLogMapper;
import com.edu.spider.mapper.TrainInfoMapper;
import com.edu.spider.service.CtripTrainService;
import com.edu.spider.util.JSONToBeanUtil;

/** 
 * @author : ljl
 * @date 创建时间：2018年9月19日 下午2:46:05 
 * @version 1.0 
 * @parameter  
 * @since  
 * @return  
 */
@Service
@Slf4j
public class CtripTrainServiceImpl implements CtripTrainService{

	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired
	private TrainInfoMapper trainInfoMapper;
	
	@Autowired
	private SearchLogMapper searchLogMapper;
	
	static int count=0;
	
	@SuppressWarnings("unchecked")
	@Override
	public void regularlyCheckTicketInformation(SearchCTripTrainDTO searchTrainDTO){		
		String url = "http://trains.ctrip.com/TrainBooking/Ajax/SearchListHandler.ashx?Action=getSearchList";
		MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
		postParameters.add("value", JSONObject.fromObject(searchTrainDTO).toString());
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");		
		HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, headers);	
		String pendingDate = searchTrainDTO.getDepartureDate()+" 23:59:59";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
		Long departureDate = null;
		try {
			departureDate = sdf.parse(pendingDate).getTime();
		} catch (ParseException e) {
			log.error(e.getMessage(),e);
		}
		Long nowDate = new Date().getTime();
		int maxTimes = Math.round((departureDate-nowDate)/(30 * 60 * 1000));			
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);			
		scheduledThreadPool.scheduleAtFixedRate(()->{				
			count++;
			log.info("=================进行第"+count+"次查询=================");
			log.info("=================剩余"+(maxTimes-count)+"次查询=================");
			ResponseEntity<String> response = restTemplate.postForEntity(url,httpEntity, String.class);		
			JSONObject json = JSONObject.fromObject(response.getBody());
			List<TrainItem> trainItemList = (List<TrainItem>) json.get("TrainItemsList");		
			searchLogMapper.insert(SearchLog.formOthers(JSONObject.fromObject(httpEntity.getBody()),url,response,response.getStatusCodeValue(),trainItemList.size()));
			log.info("=================共查询到"+trainItemList.size()+"条数据=================");
			for (int i = 0; i < trainItemList.size(); i++) {
				TrainInfo trainInfo = TrainInfo.fromTrainItems(JSONToBeanUtil.jsonToBean(String.valueOf(trainItemList.get(i)), TrainItem.class));
				trainInfoMapper.insert(trainInfo);
			}
			if(trainItemList.size()==0||count>maxTimes){
				log.info("=================任务执行完成=================");
				scheduledThreadPool.shutdown();
			}
			
		}, 0, 30 * 60, TimeUnit.SECONDS);	
	}
	
}
